/**
 * @description 微博 @ 用户关系 service
 * @author 双越老师
 */

const { AtRelation, Blog, User } = require('../db/model'); 
const { formatBlog, formatUser } = require('./_format');

/**
 * 创建@关系
 * @param {*} blogId 微博 id
 * @param {*} userId 用户 id
 */
async function createAtRelation(blogId, userId) {
    // userid @ blogid  
    const result = await AtRelation.create({
        blogId,
        userId,
        isRead: false
    })
    return result.dataValues;
}

/**
 * 获取 @ 用户的微博列表
 * @param {*} param0 
 */
async function getAtUserBlogList({ userId, pageIndex, pageSize = 10 }) {
    const result = await Blog.findAndCountAll({
        limit: pageSize,
        offset: pageSize * pageIndex,
        order: [
            ['id', 'desc']
        ],
        include: [
            {
                model: AtRelation,
                attributes: ['userId', 'blogId'],
                where: { userId }
            },
            {
                model: User,
                attributes: ['userName','nickName','picture']
            }
        ]
    })

    // 格式化
    let blogList = result.rows.map( row => row.dataValues );
    blogList = formatBlog(blogList);
    blogList = blogList.map( blogItem => {
        blogItem.user = formatUser( blogItem.user.dataValues );
        return blogItem;
    })

    return {
        count: result.count,
        blogList
    }

}

/**
 * 获取 @ 用户的微博数量 （未读的）
 * @param {*} userId 
 */
async function getAtRelationCount( userId ) {
    const result = await AtRelation.findAndCountAll({
        where: {
            userId,
            isRead: false
        }
    })
    return result.count;
}

module.exports = {
    createAtRelation,
    getAtRelationCount,
    getAtUserBlogList
}